/*************************************************************************
 * File Name:    PathSum.cc
 * Author:       zero91
 * Mail:         jianzhang9102@gmail.com
 * Created Time: 2013/11/4 9:32:14
 * 
 * Description:  
 |------------------------------------------------------------------------- 
 | Problem: Path Sum
 |
 | Given a binary tree and a sum, determine if the tree has a root-to-leaf path
 | such that adding up all the values along the path equals the given sum.
 |
 | For example:
 |
 | Given the below binary tree and sum = 22,
 |            5
 |           / \
 |          4   8
 |         /   / \
 |        11  13  4
 |       /  \      \
 |      7    2      1
 | return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
 |------------------------------------------------------------------------- 
 ************************************************************************/

#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <deque>
#include <map>
#include <set>
#include <functional>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>

using namespace std;

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool hasPathSum(TreeNode *root, int sum)
    {
        if (root == NULL) return false;
        
        sum -= root->val;
        
        if (root->left == NULL && root->right == NULL) {
            if (sum == 0) return true;
            return false;
        }
        
        bool ans = false;
    
        if (root->left != NULL) ans = hasPathSum(root->left, sum);
        if (ans) return true;
        
        if (root->right != NULL) ans = hasPathSum(root->right, sum);
        return ans;
    }
};

